<template>
  <div class="appointment">
    <el-card>
      <h2>充电预约</h2>
      <el-form :model="form" label-width="100px" v-if="isMember">
        <el-form-item label="选择站点">
          <el-select v-model="form.station" placeholder="请选择站点" @change="onStationChange">
            <el-option v-for="s in stations" :key="s.stationID" :label="s.stationLoc" :value="s.stationID" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择充电桩">
          <el-select v-model="form.pile" placeholder="请选择充电桩">
            <el-option v-for="p in piles" :key="p.pileID" :label="p.pileID + '（' + p.piletype + '）'" :value="p.pileID" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间段">
          <el-date-picker v-model="form.time" type="datetimerange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="onAppointment">预约</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-else title="仅会员可预约充电，请先升级为会员" type="warning" show-icon style="margin-bottom:20px;" />
      <el-alert v-if="msg" :title="msg" type="success" show-icon style="margin-bottom:20px;" />
    </el-card>
    <el-card style="margin-top: 30px;">
      <h3>我的充电预约</h3>
      <el-table :data="appointments" style="width:100%">
        <el-table-column prop="appointmentID" label="预约编号" />
        <el-table-column prop="stationID" label="站点" />
        <el-table-column prop="pileID" label="充电桩" />
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="status" label="状态" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status==='预约中'" size="mini" type="danger" @click="cancelAppointment(scope.row.appointmentID)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import api from '@/api';
export default {
  data() {
    return {
      appointments: [],
      stations: [],
      piles: [],
      form: { station: '', pile: '', time: [] },
      loading: false,
      msg: '',
      isMember: false
    };
  },
  async created() {
    this.loading = true;
    try {
      const user = await api.get('/user/info');
      this.isMember = user.usertype === 'MEMBER'||user.usertype === 'admin';
      this.stations = await api.get('/station/list');
      this.appointments = await api.get('/appointment/list');
    } catch (e) {
      this.msg = '初始化失败';
    }
    this.loading = false;
  },
  methods: {
    async onStationChange(val) {
      if (val) {
        this.piles = await api.get('/pile/list?stationID=' + val);
      } else {
        this.piles = [];
      }
    },
    async onAppointment() {
      if (!this.form.station || !this.form.pile || !this.form.time.length) {
        this.msg = '请填写完整预约信息';
        return;
      }
      this.loading = true;
      try {
        const res = await api.post('/appointment/add', {
          stationID: this.form.station,
          pileID: this.form.pile,
          startTime: this.form.time[0],
          endTime: this.form.time[1]
        });
        if (res && res.success) {
          this.msg = '预约成功！预约码：' + (res.code || '');
          this.appointments = await api.get('/appointment/list');
        } else {
          this.msg = res && res.msg ? res.msg : '预约失败';
        }
      } catch (e) {
        this.msg = '预约失败';
      }
      this.loading = false;
    },
    async cancelAppointment(id) {
      this.loading = true;
      try {
        await api.post('/appointment/cancel', { appointmentID: id });
        this.msg = '取消成功';
        this.appointments = await api.get('/appointment/list');
      } catch (e) {
        this.msg = '取消失败';
      }
      this.loading = false;
    }
  }
};
</script>
<style scoped>
.appointment { max-width: 900px; margin: 40px auto; }
</style>
